package GUI;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;
/**
 * Add a new specific book to the library
 * @author Lidor
 *
 */
public class AddBookToStockGUI extends JPanel {
	public JTextField textBookName;
	public JTextField textAuthor;
	public JTextField textEdition;
	public JTextField textPrintDate;
	public JTextField textSubject;
	public JTextField textSummary;
	public JTextField textPurchaseDate;
	public JTextField textShelf;
	public JFileChooser chooser;
	public JTextField textFieldSelectFile;
	public JRadioButton rdbtnYes;
	public File file;
	public MainFrame mf;
	public byte [] bytesArray;
	public int length;

	/**
	 * Create the panel.
	 * @param M main frame of the program
	 */
	public AddBookToStockGUI(MainFrame M) {
		setLayout(null);
		mf=M;
		file=null;
		chooser= new JFileChooser();
		
		JLabel lblAddBookTo = new JLabel("Add Book To Stock");
		lblAddBookTo.setFont(new Font("Segoe UI", Font.BOLD, 16));
		lblAddBookTo.setBounds(224, 26, 211, 14);
		add(lblAddBookTo);
		
		JLabel lblBookName = new JLabel("Book Name:");
		lblBookName.setBounds(55, 78, 122, 14);
		add(lblBookName);
		
		JLabel lblAuthors = new JLabel("Author(s):");
		lblAuthors.setBounds(55, 103, 122, 14);
		add(lblAuthors);
		
		JLabel lblEdition = new JLabel("Edition:");
		lblEdition.setBounds(55, 128, 122, 14);
		add(lblEdition);
		
		JLabel lblPrintDate = new JLabel("Print Date:");
		lblPrintDate.setBounds(55, 153, 122, 14);
		add(lblPrintDate);
		
		JLabel lblSubjects = new JLabel("Subject(s):");
		lblSubjects.setBounds(55, 178, 122, 14);
		add(lblSubjects);
		
		JLabel lblSummary = new JLabel("Summary:");
		lblSummary.setBounds(55, 203, 122, 14);
		add(lblSummary);
		
		
		textBookName = new JTextField();
		textBookName.setBounds(187, 75, 170, 20);
		add(textBookName);
		textBookName.setColumns(10);
		
		textAuthor = new JTextField();
		textAuthor.setBounds(187, 100, 170, 20);
		add(textAuthor);
		textAuthor.setColumns(10);
		
		textEdition = new JTextField();
		textEdition.setBounds(187, 125, 170, 20);
		add(textEdition);
		textEdition.setColumns(10);
		
		textPrintDate = new JTextField();
		textPrintDate.setBounds(187, 150, 170, 20);
		add(textPrintDate);
		textPrintDate.setColumns(10);

		
		textSubject = new JTextField();
		textSubject.setBounds(187, 175, 170, 20);
		add(textSubject);
		textSubject.setColumns(10);
		
		textSummary = new JTextField();
		textSummary.setBackground(new Color(255, 255, 255));
		textSummary.setBounds(187, 200, 353, 143);
		add(textSummary);
		textSummary.setColumns(10);
		
		JLabel lblRated = new JLabel("Rated:");
		lblRated.setBounds(55, 358, 122, 14);
		add(lblRated);
		
		JLabel lblPurchaseDate = new JLabel("Purchase Date:");
		lblPurchaseDate.setBounds(55, 383, 122, 14);
		add(lblPurchaseDate);
		
		JLabel lblShelf = new JLabel("Shelf:");
		lblShelf.setBounds(55, 408, 122, 14);
		add(lblShelf);
		
		JLabel lblTableOfContents = new JLabel("Table of Contents:");
		lblTableOfContents.setBounds(55, 433, 122, 14);
		add(lblTableOfContents);
		
		textPurchaseDate = new JTextField();
		textPurchaseDate.setBounds(187, 380, 170, 20);
		add(textPurchaseDate);
		textPurchaseDate.setColumns(10);
		
		
		textShelf = new JTextField();
		textShelf.setBounds(187, 405, 170, 20);
		add(textShelf);
		textShelf.setColumns(10);
		
		textFieldSelectFile = new JTextField();
		textFieldSelectFile.setEditable(false);
		textFieldSelectFile.setBounds(187, 430, 231, 20);
		add(textFieldSelectFile);
		textFieldSelectFile.setColumns(10);
		
		JButton btnBrowse = new JButton("Browse...");
		btnBrowse.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				 int r = chooser.showOpenDialog(new JFrame());
				    if (r == JFileChooser.APPROVE_OPTION) {
				      String name = chooser.getSelectedFile().getAbsolutePath();
				      textFieldSelectFile.setText(name);
				      file=chooser.getSelectedFile();
				      length=(int) file.length();
				      FileInputStream fis = null;
					try {
						fis = new FileInputStream(file);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				      bytesArray = new byte[length];
				      try {
						fis.read(bytesArray, 0, length);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				    }
			}
		});
		btnBrowse.setBounds(428, 429, 112, 23);
		add(btnBrowse);
		
		JButton btnFinish = new JButton("Finish");
		btnFinish.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ArrayList<Object> send= new ArrayList<>();
				
				if(checkName(textBookName.getText())==1 &&
						checkName(textAuthor.getText())==1 &&
								checkNum(textEdition.getText())==1 &&
								checkDate(textPrintDate.getText())==1 &&
								checkName(textSummary.getText())==1 &&
								checkName(textSubject.getText())==1 &&
								checkDate(textPurchaseDate.getText())==1 &&
								checkShelf(textShelf.getText())==1 &&
								!textFieldSelectFile.getText().equals(""))
						{
							Calendar c=Calendar.getInstance();
							DateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
							String today=sdf.format(c.getTime());
							if(today.compareTo(textPurchaseDate.getText())>=0 && textPurchaseDate.getText().compareTo(textPrintDate.getText())>=0)
							{
								send.add("2");
								send.add("addBook");
								send.add(textBookName.getText());
								send.add(textAuthor.getText());
								send.add(textEdition.getText());
								send.add(textPrintDate.getText());
								send.add(textSummary.getText());
								if(rdbtnYes.isSelected())
									send.add("yes");
								else
									send.add("no");
								send.add(textPurchaseDate.getText());
								send.add(textShelf.getText());
								send.add(bytesArray);
								send.add(length);
								send.add(textSubject.getText());
								init();
								mf.client.accept(send);
							}
							else JOptionPane.showMessageDialog(null, "wrong date!", "Program", JOptionPane.ERROR_MESSAGE);
						}
				else
					JOptionPane.showMessageDialog(null, "Incorrect Information Was Entered!", "Program", JOptionPane.ERROR_MESSAGE);
			}
		});

		btnFinish.setBounds(171, 471, 89, 23);
		add(btnFinish);
		
		JButton btnClear = new JButton("Clear");
		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				init();
			}
		});
		btnClear.setBounds(311, 471, 89, 23);
		add(btnClear);

		ImageIcon img = new ImageIcon(getClass().getResource(
                "/util/grad2.jpg"));
		
		rdbtnYes = new JRadioButton("Yes");
		rdbtnYes.setBounds(187, 351, 49, 23);
		add(rdbtnYes);
		JLabel picLabel = new JLabel(img);
		picLabel.setLocation(0, 0);
		picLabel.setSize(683, 575);
		add(picLabel);
	}
	
	/**
	 * initialize all the text fields
	 */
	public void init()
	{
		textBookName.setText("");
		textAuthor.setText("");
		textEdition.setText("");
		textPrintDate.setText("YYYY-MM-DD");
		textSubject.setText("");
		textSummary.setText("");
		textPurchaseDate.setText("YYYY-MM-DD");
		textShelf.setText("");
		textFieldSelectFile.setText("");
		rdbtnYes.setSelected(false);
		file=null;
		bytesArray=null;
		length=0;
	}
	
	/**
	 * check for string validity (need to contain only characters)
	 * @param text given specific string and checks for its validity
	 * @return validity status
	 */
	public int checkName(String text)
	{
	  final char[] chars = text.toCharArray();
	  for (int x = 0; x < chars.length; x++) {      
	    final char c = chars[x];
	    if ((c >= 'a') && (c <= 'z')) continue; // lowercase
	    if ((c >= 'A') && (c <= 'Z')) continue; // uppercase
	    return 0;
	  }  
	  return 1;
	}
	
	/**
	 * check for string validity (need to contain only numbers)
	 * @param num given specific string and checks for its validity
	 * @return validity status
	 */
	public int checkNum(String num){
		try  
		{  
			@SuppressWarnings("unused")
			int i = Integer.parseInt(num);  
		}  
		catch(NumberFormatException nfe)  
		{  
			return 0;  
		}  
		return 1;  
	}
	
	/**
	 * check for string validity (needs to contain date in format: YYYY-MM-DD)
	 * @param date given specific string and checks for its validity
	 * @return validity status
	 */
	public int checkDate(String date){
        String expression = "^\\(?(\\d{4})\\)?[- ]?(\\d{2})[- ]?(\\d{2})$";
        CharSequence inputStr = date;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        boolean matchFound = matcher.matches();

		if(matchFound) return 1;
		else return 0;
    }
	
	/**
	 * check for string validity (can contain characters and numbers)
	 * @param text given specific string and checks for its validity
	 * @return validity status
	 */
	public int checkShelf(String text)
	{
	  final char[] chars = text.toCharArray();
	  for (int x = 0; x < chars.length; x++) {      
	    final char c = chars[x];
	    if ((c >= 'a') && (c <= 'z')) continue; // lowercase
	    if ((c >= 'A') && (c <= 'Z')) continue; // uppercase
	    if ((c >= '0') && (c <= '9')) continue; // numers
	    return 0;
	  }  
	  return 1;
	}
}
